package com.ewanghuiju.app.ui.main.activity;

import android.annotation.SuppressLint;
import android.widget.ImageView;
import android.widget.TextView;

import com.ewanghuiju.app.R;
import com.ewanghuiju.app.base.SimpleActivity;
import com.ewanghuiju.app.component.ImageLoader;
import com.ewanghuiju.app.ui.main.dao.OnSplashListener;
import com.gyf.immersionbar.ImmersionBar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @author sj  qq:751943509
 * @class describe
 * @time 2020/2/19
 */
public class AdActivity extends SimpleActivity implements Observer<Long> {

    @BindView(R.id.iv_splash)
    ImageView ivSplash;
    @BindView(R.id.tv_time)
    TextView tvTime;


    private static String mKey = "TotalTime";

    private long mTotalTime = 3;

    private Disposable mSubscribe;
    private OnSplashListener mOnSplashListener;

    private boolean mIsFinish = false;


    @Override
    protected int getLayout() {
        return R.layout.activity_ad;
    }

    @Override
    protected void initEventAndData() {
        ImmersionBar.setTitleBar(mContext, tvTime);
        ImageLoader.load(mContext,R.mipmap.bg_splash, ivSplash);
        startCountDown();
    }
    /**
     * 关闭当前页面
     */
    private void mfinish() {
        finish();
        mIsFinish = true;
    }

    /**
     * 开启倒计时
     */
    private void startCountDown() {
        Observable.interval(1, TimeUnit.SECONDS)
                .map(aLong -> mTotalTime - aLong)
                .take(mTotalTime + 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    /**
     * 关闭倒计时
     */
    private void stopCountDown() {
        if (mSubscribe != null && !mSubscribe.isDisposed()) {
            mSubscribe.dispose();
            mSubscribe = null;
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        mSubscribe = d;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onNext(Long aLong) {
        tvTime.setText("我是" + aLong + "s欢迎页，点我可以关闭");
        if (mOnSplashListener != null) {
            mOnSplashListener.onTime(aLong, mTotalTime);
        }
    }

    @Override
    public void onError(Throwable e) {
        mfinish();
    }

    @Override
    public void onComplete() {
        mfinish();
    }

    public void setOnSplashListener(OnSplashListener onSplashListener) {
        this.mOnSplashListener = onSplashListener;
    }

    public boolean isFinish() {
        return mIsFinish;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopCountDown();
    }

}
